package com.world.cat.controller.sys;

import com.world.cat.enums.FileType;
import com.world.cat.model.sys.User;
import com.world.cat.model.sys.UserRole;
import com.world.cat.model.sys.PrivateFile;;
import com.world.cat.pojo.UploadFileResponse;
import com.world.cat.service.generate.FieldService;
import com.world.cat.service.sys.PrivateFileService;
import com.world.cat.service.sys.RoleService;
import com.world.cat.service.sys.UserService;
import com.world.cat.service.sys.UserRoleService;
import com.world.cat.app.utils.qiniu.UploadUtil;
import com.world.cat.app.utils.qiniu.QiniuUtil;
import com.world.cat.app.utils.qiniu.ReturnBody;
import com.world.common.pojo.Result;
import com.world.common.pojo.WorldPage;
import com.world.common.util.NumberUtil;
import com.world.common.util.SessionUtil;
import com.world.common.util.sign.MD5Util;
import com.world.core.exception.WorldValidateException;
import net.sf.json.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.UUID;

/**
 * 用户管理
 */
@Controller
@RequestMapping(value = "/sys/user", name = "用户管理")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private UserRoleService userRoleService;
    @Resource
    private PrivateFileService privateFileService;

    @RequestMapping(value = "/home")
    public String home(Model model) {
        model.addAttribute("fieldMap", FieldService.getFieldMap(User.class));
        model.addAttribute("qClassActions", FieldService.getClassActionInfo(User.class));
        return "sys/user/home";
    }

    @RequestMapping(value = "/edit", name = "编辑")
    public String edit(Model model, String id) throws Exception {
        model.addAttribute("fieldMap", FieldService.getFieldMap(User.class));
        User object = userService.get(id);
        model.addAttribute("obj", object);
        return "/sys/user/edit";
    }

    @RequestMapping(value = "/add", name = "添加")
    public String add(Model model) throws Exception {
        model.addAttribute("fieldMap", FieldService.getFieldMap(User.class));
        return "/sys/user/add";
    }

    @RequestMapping(value = "/view", name = "查看")
    public String view(Model model, String id) throws Exception {
        model.addAttribute("fieldMap", FieldService.getFieldMap(User.class));
        User object = userService.get(id);
        model.addAttribute("obj", object);
        return "/sys/user/view";
    }

    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String params, WorldPage worldPage, HttpServletRequest request) throws Exception {
        //jqxgrid是用这个值来传递page和row的
        int pagenum = NumberUtil.intValue(request.getParameter("pagenum")) + 1;
        int pagesize = NumberUtil.intValue(request.getParameter("pagesize"));
        worldPage.setPageIndex(pagenum);
        worldPage.setPageSize(pagesize);
        worldPage.setProperties("createTime");
        Page<User> pages = userService.findPage(User.class, params, worldPage.getPageRequest());
        return pages;
    }

    @RequestMapping(value = "/listBusiHandler")
    @ResponseBody
    public Object listHandler(String params, WorldPage worldPage, HttpServletRequest request) throws Exception {
        //jqxgrid是用这个值来传递page和row的
        int pagenum = NumberUtil.intValue(request.getParameter("pagenum")) + 1;
        int pagesize = NumberUtil.intValue(request.getParameter("pagesize"));
        worldPage.setPageIndex(pagenum);
        worldPage.setPageSize(pagesize);
        worldPage.setProperties("createTime");
        Page<User> pages = userService.findHandlerPage(User.class, params, worldPage.getPageRequest());
        return pages;
    }

    @RequestMapping(value = "/role")
    public String userRole(Model model, String userId) {
        User user = userService.findById(userId);
        List<UserRole> userRole = userRoleService.findUserRole(userId);
        model.addAttribute("userRole", userRole);
        model.addAttribute("userRoleJson", JSONArray.fromObject(userRole).toString());
        model.addAttribute("num", userRole.size());
        model.addAttribute("user", user);
        return "back/sys/user-role";
    }

    //个人设置
    @RequestMapping(value = "/set")
    public String set(Model model, String userId) {
        return "sys/user/set";
    }

    //个人中心
    @RequestMapping(value = "/center")
    public String center(Model model) {
        User user = userService.findByUsername(SessionUtil.getUserName());
        model.addAttribute("user", user);
        return "sys/user/center";
    }

    @RequestMapping(value = "/role/save", name = "选择角色")
    @ResponseBody
    public Object saveUserRole(String userId, String[] roleIds) {
        roleService.saveUserRole(userId, roleIds);
        return new Result(true, "保存成功");
    }

    @RequestMapping(value = "/roles")
    @ResponseBody
    public Object getRoles(String id) {
        Result result = userService.getUserRoles(id);
        return result;
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Object save(String params) throws Exception {
        Result result = userService.save(User.class, params);
        return result;
    }

    @RequestMapping(value = "/del", name = "删除")
    @ResponseBody
    public Object del(String[] ids) throws Exception {
        try {
            userService.del(ids);
        } catch (Exception e) {
            return new Result(false, "删除失败");
        }
        return new Result(true);
    }

    @RequestMapping(value = "/modifyPassword")
    @ResponseBody
    public Object modifyPassword(String oldPassword, String newPassword, String rePassword) throws Exception {
        Result result = userService.modifyPassword(SessionUtil.getUserName(), oldPassword, newPassword, rePassword);
        return result;
    }

    @RequestMapping(value = "/password/modify")
    @ResponseBody
    public Object passwordModify(String id, String oldPassword, String newPassword, String rePassword) throws Exception {
        User user = userService.findById(id);
        Result result = userService.modifyPassword(user.getUsername(), oldPassword, newPassword, rePassword);
        return result;
    }


    //上传头像
    @RequestMapping(value = "/uploadAvatar")
    @ResponseBody
    public Object uploadAvatar(HttpSession session, HttpServletRequest request) throws Exception {
        Result result = new Result();
        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartHttpServletRequest.getFile("avatar");
            String objId = request.getParameter("objId");

            try {
                if (file == null || file.isEmpty()) {
                    result.setMsg("上传文件为空");
                    return result;
                }
                String fileName = file.getOriginalFilename();
                if (StringUtils.isBlank(fileName)) {
                    fileName = MD5Util.md5(UUID.randomUUID().toString());
                }
                String filePathPrefix = QiniuUtil.getQiniuPathPrefix();
                //文件上传七牛
                ReturnBody returnBody = QiniuUtil.privateBucketFileUploadByByteArr(file.getBytes(), filePathPrefix + fileName);
                //文件存在本地
                QiniuUtil.saveLocalPrivateFile(file, filePathPrefix, fileName);
                //保存文件记录
                PrivateFile privateFile = privateFileService.savePrivateFile(SessionUtil.getUserName(), returnBody, filePathPrefix, fileName, FileType.DOC, objId);
                userService.saveAvatar(SessionUtil.getUserName(), privateFile.getId());
                session.setAttribute("avatar", UploadUtil.getFullDownLoadUrlByFileId(privateFile.getId()));
                result.setSuccess(true);
                UploadFileResponse data = new UploadFileResponse(privateFile);
                result.setData(data);
                return result;
            } catch (WorldValidateException e) {
                result.setMsg(e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
                result.setMsg(e.getMessage());
            }
            return result;
        }

        return result;
    }
}
